// 设置管理Hook
// 提供设置相关的操作和状态管理

import { useCallback, useEffect } from 'react';
import { useSettingsStore } from '../stores/settingsStore';
import { SettingsCategory, SettingChangeEvent } from '../types/settings';

export const useSettings = () => {
  const {
    settings,
    isSettingsDialogOpen,
    activeCategory,
    isDirty,
    searchQuery,
    searchResults,
    getSetting,
    setSetting,
    resetSetting,
    resetCategory,
    resetAllSettings,
    updateSettings,
    validateSetting,
    validateAllSettings,
    searchSettings,
    clearSearch,
    exportSettings,
    importSettings,
    openSettingsDialog,
    closeSettingsDialog,
    setActiveCategory,
    getChangeHistory,
    clearHistory,
    onSettingChange
  } = useSettingsStore();

  // 打开设置对话框
  const openSettings = useCallback((category?: SettingsCategory) => {
    openSettingsDialog(category);
  }, [openSettingsDialog]);

  // 关闭设置对话框
  const closeSettings = useCallback(() => {
    closeSettingsDialog();
  }, [closeSettingsDialog]);

  // 获取设置值的类型安全版本
  const getSettingValue = useCallback(<T = any>(settingId: string, defaultValue?: T): T => {
    const value = getSetting(settingId) as T;
    return value !== undefined ? value : (defaultValue as T);
  }, [getSetting]);

  // 批量更新设置
  const batchUpdateSettings = useCallback((updates: Record<string, any>) => {
    Object.entries(updates).forEach(([settingId, value]) => {
      setSetting(settingId, value);
    });
  }, [setSetting]);

  // 监听设置变化
  const subscribeToSettingChanges = useCallback((
    callback: (event: SettingChangeEvent) => void
  ) => {
    return onSettingChange(callback);
  }, [onSettingChange]);

  // 检查设置是否已修改
  const isSettingModified = useCallback((settingId: string): boolean => {
    const currentValue = getSetting(settingId);
    // 这里需要获取默认值进行比较，暂时返回false
    // 实际实现中应该从设置定义中获取默认值
    return false;
  }, [getSetting]);

  // 获取设置验证错误
  const getSettingErrors = useCallback((settingId: string) => {
    const currentValue = getSetting(settingId);
    const validation = validateSetting(settingId, currentValue);
    return validation.errors;
  }, [getSetting, validateSetting]);

  // 应用主题设置
  const applyThemeSettings = useCallback(() => {
    const theme = getSettingValue('appearance.theme', 'auto') as 'light' | 'dark' | 'auto';
    const followSystem = getSettingValue('appearance.followSystemTheme', true);

    const root = document.documentElement;

    if (theme === 'auto' && followSystem) {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      root.classList.toggle('dark', prefersDark);
    } else {
      root.classList.toggle('dark', theme === 'dark');
    }
  }, [getSettingValue]);

  // 应用编辑器设置
  const applyEditorSettings = useCallback(() => {
    // 这里可以应用编辑器相关的设置
    // 例如字体大小、主题等
    const fontSize = getSettingValue('editor.fontSize', 14);
    const fontFamily = getSettingValue('editor.fontFamily', 'Consolas, "Courier New", monospace');
    
    // 应用到Monaco编辑器或其他编辑器实例
    // 这需要与编辑器实例管理器集成
  }, [getSettingValue]);

  // 初始化设置
  useEffect(() => {
    applyThemeSettings();
    applyEditorSettings();
  }, [applyThemeSettings, applyEditorSettings]);

  // 监听主题设置变化
  useEffect(() => {
    const unsubscribe = subscribeToSettingChanges((event) => {
      if (event.settingId.startsWith('appearance.theme') || 
          event.settingId === 'appearance.followSystemTheme') {
        applyThemeSettings();
      }
      
      if (event.settingId.startsWith('editor.')) {
        applyEditorSettings();
      }
    });

    return unsubscribe;
  }, [subscribeToSettingChanges, applyThemeSettings, applyEditorSettings]);

  // 监听系统主题变化
  useEffect(() => {
    const followSystem = getSettingValue('appearance.followSystemTheme', true);
    const theme = getSettingValue('appearance.theme', 'auto');
    
    if (!followSystem || theme !== 'auto') {
      return;
    }

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handleThemeChange = () => {
      applyThemeSettings();
    };

    mediaQuery.addEventListener('change', handleThemeChange);
    
    return () => {
      mediaQuery.removeEventListener('change', handleThemeChange);
    };
  }, [getSettingValue, applyThemeSettings]);

  return {
    // 状态
    settings,
    isSettingsDialogOpen,
    activeCategory,
    isDirty,
    searchQuery,
    searchResults,
    
    // 基础操作
    getSetting: getSettingValue,
    setSetting,
    resetSetting,
    resetCategory,
    resetAllSettings,
    updateSettings,
    batchUpdateSettings,
    
    // 验证
    validateSetting,
    validateAllSettings,
    isSettingModified,
    getSettingErrors,
    
    // 搜索
    searchSettings,
    clearSearch,
    
    // 导入导出
    exportSettings,
    importSettings,
    
    // UI控制
    openSettings,
    closeSettings,
    setActiveCategory,
    
    // 历史记录
    getChangeHistory,
    clearHistory,
    
    // 监听器
    subscribeToSettingChanges,
    
    // 应用设置
    applyThemeSettings,
    applyEditorSettings
  };
};
